__author__ = 'F3285189'

from tkinter import *
from random import randint
import codecs

class UnknownCommand(Exception): pass

class Files():
    ""
    def __init__(self, filename):
        self.file= codecs.open(filename,'rU','utf-8')

    def getline(self):
        return self.file.readline()

class textWriter(Tk):
    ""
    def __init__(self, bgc, fgc, file):
        ""
        "Initialise TK widget by calling the TK init"
        Tk.__init__(self)
        "Initialise scrollbar sub widget"
        self.scrollbar = Scrollbar(self)
        self.scrollbar.pack(side=RIGHT, fill=Y)
        "Initialise text sub widget"
        self.text = Text(self, wrap=WORD, width=140, background=bgc, foreground=fgc, yscrollcommand=self.scrollbar.set)
        self.text.pack(side=LEFT, fill=BOTH)
        self.scrollbar.config(command=self.text.yview)
        self.source = file
        self.sindex = 0
        self.start()
        self.time_out_counter=0

    def start(self):
        "Seeds first event"
        self.after(10, self.displayfeed)

    def displayfeed(self):
        "Reads text from file and displays info"
        string = self.source.getline()
        #TODO: Add here a check for a full line
        print (string)
        if string:
            self.after(1, self.cput, string)
        elif self.time_out_counter < 10: #TODO this need to be parametrized
            self.after(10, self.displayfeed)
            self.time_out_counter+=1
        else:
            print("Timeout value reached!")
            self.after(10, self.displayfeed)
            self.time_out_counter=0

    def cput(self, string):
        "Displays the input string one char at a time at random intervals"
        try:
            self.text.insert(END, string[self.sindex])
        except Exception as e:
            print('WARNING:',e.args, e.__class__)
            self.text.insert(END, "<emo>")
            print(string[self.sindex].encode('utf-8'))
        finally:
            self.sindex += 1
            if self.sindex < len(string):
                self.after((10+(randint(5, 10)*(randint(1, 8)))), self.cput, string)
            else:
                self.sindex = 0
                self.after(10, self.displayfeed)
                self.text.yview_moveto(1.0)


myfiles = Files("posts.txt")

root = textWriter("black", "yellow", myfiles)
root.mainloop()